package com.kongyz.registry;


import org.apache.zookeeper.*;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * @author kongyz
 * @date 2018/7/12 22:23
 * @Description:
 */
public class CreateGroup {
    private static final int SESSION_TIMEOUT=5000;
    public ZooKeeper zk;
    private CountDownLatch connectedSignal=new CountDownLatch(1);

    public void connect(String hosts) throws IOException, InterruptedException {
        zk=new ZooKeeper(hosts, SESSION_TIMEOUT, new Watcher() {
            public void process(WatchedEvent watchedEvent) {
                if(watchedEvent.getState()== Event.KeeperState.SyncConnected){
                    connectedSignal.countDown();
                }
            }
        });
        connectedSignal.await();
    }


    /**
     * 创建分组
     * @param groupName
     * @throws KeeperException
     * @throws InterruptedException
     */
    public void create(String groupName) throws KeeperException, InterruptedException {
        String path="/"+groupName;
        String createPath=zk.create(path,null,ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        System.out.println("Created :"+createPath);
    }

    public void join(String groupName,String memberName) throws KeeperException, InterruptedException {
        String path="/"+groupName+"/"+memberName;
        byte[] data=("分组"+memberName).getBytes();
        String createPath=zk.create(path,data,ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT);
        System.out.println(createPath);
    }


    public void close() throws InterruptedException {
        zk.close();
    }


    public static void main(String[] args) {
        CreateGroup createGroup=new CreateGroup();
        try {
            createGroup.connect("192.168.88.66");
            Thread.sleep(100);
//            createGroup.create("kongyz");
            createGroup.join("kongyz","test");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (KeeperException e) {
            e.printStackTrace();
        }finally {
            try {
                createGroup.close();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }


}
